package club.gskj.gulimall.gateway.config;

import club.gskj.common.exception.BizCodeEnume;
import club.gskj.common.utils.R;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/***
 *  sentinel 网关阻塞处理器
 */
@Configuration
public class SentinelGateWayConfig {

    // TODO 响应式编程
    // GatewayCallbackManager
    public SentinelGateWayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            // 网格限流后的请求，会调用该回调方法 Mono Flux
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                // 自定义返回限流数据
                R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg());
                String s = JSON.toJSONString(error);
                // 使用 Spring5 响应式编程特性
                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(s), String.class);
                return body;
            }
        });
    }
}
